﻿using Autofac;
using Common;
using DBContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLine.Common;
using ZoneLine.Models;
using ZoneLine.Models.PrintRecord;

namespace ZoneLine.Printers
{
    public class BQLHPrinter : IPrinter
    {
        public string PrintLabel(string printTemplatePath, string printerName, int index)
        {
            var (paras, code) = GetPara(index);

            PrinterHelper.PrinterLabel(printTemplatePath, printerName, paras);
            return code;
        }

        private (Dictionary<string, string>, string) GetPara(int index)
        {
            var config = ContainerServer.Container.Resolve<PrintConfigTotal>();
            var lxConfig = config.BqqcLHConfig;
            var paras = new Dictionary<string, string>();
            paras.Add("LJH_N3", lxConfig.PartNo);
            paras.Add("GYSDM_N3", lxConfig.SupplyNo);
            paras.Add("GKBJ_N3", lxConfig.ControllerCode);

            var batchCode = GetBatchCode(index);
            paras.Add("PCBM_N3", batchCode);

            var code = $"{lxConfig.SupplyNo}{batchCode}K{lxConfig.PartNo}";
            paras.Add("EWM_N3", code);
            var para = StationEnableConfig.GetPara();
            if (Cache.WorkDirection == WorkDirectionEnum.Left)
            {
                paras.Add("QHZY_N3", "L");
            }
            else
            {
                paras.Add("QHZY_N3", "R");
            }
            BQLHRecord bQLHRecord = new BQLHRecord();
            bQLHRecord.SerialNumber = index;
            bQLHRecord.Code = code;
            bQLHRecord.BatchCode = lxConfig.BatchCode;
            bQLHRecord.ControllerCode = lxConfig.ControllerCode;
            bQLHRecord.PartName = lxConfig.PartName;
            bQLHRecord.PartNo = lxConfig.PartNo;
            bQLHRecord.SupplyNo = lxConfig.SupplyNo;
            bQLHRecord.TemplatePath = lxConfig.TemplatePath;
            bQLHRecord.TemplatePathR = lxConfig.TemplatePathR;
            DBContext.DbConfig.DbContext.Insert<BQLHRecord>(bQLHRecord).ExecuteInserted();
            return (paras, code);
        }

        public void PrintLabelShow(string path, string printerName, int index)
        {
            var (paras, code) = GetPara(index);

            PrinterHelper.PrinterLabelShow(path, printerName, paras);
        }

        private string GetBatchCode(int index)
        {
            var s = (byte)((DateTime.Now.Year - 2010) + 64);
            var year = Encoding.ASCII.GetString(new byte[] { s }); var mouths = DateTime.Now.Month.ToString("00");
            var days = DateTime.Now.Day.ToString("00");
            var indexs = index.ToString("00000");
            return $"{year}{mouths}{days}{indexs}";
        }
    }
}